package com.api.workflow.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.workflow.util.YNHttpUtils;
import weaver.common.util.string.StringUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/*
 * OA-12.费用报销审批申请
 *
 * 接口5OA与SAP付款申请接口
 * */
public class YN12FII002ActionN extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        BaseBean baseBean = new BaseBean();
        String requestid = requestInfo.getRequestid();
        String workflowid = requestInfo.getWorkflowid();

        int formid = requestInfo.getRequestManager().getFormid();
        int formidAbs = Math.abs(formid);// 流程表单id绝对值
        String tableDBName = "formtable_main_" + formidAbs;

        // 主表数据
        MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
        Property[] property = mainTableInfo.getProperty();
        //这里是存储了主表全部的数据  可自行修改存储结构
        Map<String, Object> mainTableInfoMap = new HashMap<>();
        for (int i = 0; i < property.length; i++) {
            String name = property[i].getName().toLowerCase();
            mainTableInfoMap.put(name, Util.null2String(property[i].getValue()));
        }
        baseBean.writeLog("=============mainTableInfoMap:" + JSONObject.toJSONString(mainTableInfoMap));

        //明细表数据
        List<Map<String, Object>> detailTableMap = getMaps(requestInfo);
        baseBean.writeLog("=============detailTableMap:" + JSONObject.toJSONString(detailTableMap));

        //业务逻辑
        String departmentid = "";
        try {
            RecordSet rs = new RecordSet();
            Map<String, Object> map = new HashMap<>();
            //ZYF
            String zyf = String.valueOf(mainTableInfoMap.get("zyf"));
            map.put("ZSFFK","N");
            //更新znf
            String update1 = "update " + tableDBName + " set zyf = 'N' where requestid = '"+requestid+"'";
            baseBean.writeLog("lyh:OA-21==============update1"+update1);
            rs.executeUpdate(update1);

            map.put("ZBONO", mainTableInfoMap.get("lcbh"));
            map.put("ZREID", requestid);
            String sqr = mainTableInfoMap.get("sqr").toString();
            String sql1 = "select * from hrmresource where id = '" + sqr + "'";
            baseBean.writeLog("lyh================sql1" + sql1);
            rs.execute(sql1);
            if (rs.next()) {
                departmentid=rs.getString("departmentid");
                map.put("ZHRNO", rs.getString("workcode"));

                map.put("ZNAME", rs.getString("lastname"));
            }

            map.put("LIFNR", mainTableInfoMap.get("sjbxyg"));
            String sqbm = "";
            Object sqbm1 = mainTableInfoMap.get("sqbm");
            if (Objects.nonNull(sqbm1)) {
                sqbm = sqbm1.toString();
                String sql2 = "select * from hrmdepartment where id = '" + sqbm + "'";
                baseBean.writeLog("lyh==============sql2" + sql2);
                rs.execute(sql2);
                if (rs.next()) {
                    map.put("ZSQBM", rs.getString("departmentcode"));
                    map.put("ZBMMS", rs.getString("departmentname"));
                    baseBean.writeLog("lyh============ZSQBM" + rs.getString("departmentcode") + "ZBMMS:" + rs.getString("departmentname"));
                }
            }


            map.put("ZBOTYP", mainTableInfoMap.get("djlx"));
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery("select fkyxzh from uf_gsdmb_dt1 where id=?",mainTableInfoMap.get("xzskzh"));
            recordSet.next();
            String fkyxzh = Util.null2String(recordSet.getString("fkyxzh"));
            map.put("ZBANK", fkyxzh);
            map.put("WAERS", mainTableInfoMap.get("bz1"));
            map.put("BUKRS", mainTableInfoMap.get("gsdm"));
            map.put("ZAPDAT", mainTableInfoMap.get("sqrq"));
            String xzskzh = String.valueOf(mainTableInfoMap.get("xzskzh"));
            if (!StringUtil.isNullOrEmpty(xzskzh)) {
                RecordSet recordSet1 = new RecordSet();
                recordSet1.executeQuery("select * from uf_gsdmb_dt1 where id=?",xzskzh);
                recordSet1.next();
                map.put("ZBANK", recordSet1.getString("fkyxzh"));

            }


            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formattedDate = currentDate.format(formatter);
            map.put("ZPASSDAT", formattedDate);//调接口当天日期

            map.put("ZBKTXT", mainTableInfoMap.get("fksm"));
            map.put("ZLSCH", mainTableInfoMap.get("fkfs"));
            map.put("ZAZBET", mainTableInfoMap.get("hjzje"));
            map.put("NUMPG", mainTableInfoMap.get("fpzs"));
            map.put("ZHXSUM", mainTableInfoMap.get("cxjzje"));
            map.put("BKVID", mainTableInfoMap.get("yxbs"));
            map.put("ZPARBANKL", mainTableInfoMap.get("skzhlxh"));
            map.put("ZPARBANKN", mainTableInfoMap.get("skrzh"));
            map.put("ZPARKOINH", mainTableInfoMap.get("zhcyr"));
            map.put("ZPARBANKA", mainTableInfoMap.get("zhmc"));


            //通过申请部门ID查询部门信息
            String sql2 = "select * from hrmdepartment where id = '" + departmentid + "'";
            baseBean.writeLog("lyh:OA-10==============sql2"+sql2);
            rs.execute(sql2);
            if (rs.next()) {
                map.put("ZSQBM", rs.getString("departmentcode"));
                map.put("ZBMMS", rs.getString("departmentname"));
                baseBean.writeLog("lyh:OA-12============ZSQBM" + rs.getString("departmentcode") + "ZBMMS:" + rs.getString("departmentname"));
            }



            for (Map<String, Object> stringObjectMap : detailTableMap) {
                String detailTableName = stringObjectMap.get("detailTableName").toString();

                if ( "dt2".equals(detailTableName.substring(detailTableName.length()-3) )) {

                    map.put("ZZBONO", stringObjectMap.get("jkdh"));
                    break;
                }
            }

            //明细表数据

            List<Map> list = new ArrayList<>();
            int count = 1;
            for (Map<String, Object> objectMap : detailTableMap) {
                Map<String, Object> ITEM = new HashMap<>();
                String detailTableName = objectMap.get("detailTableName").toString();
                if ("dt1".equals(detailTableName.substring(detailTableName.length()-3))){
                    ITEM.put("BUZEI", count);

                    ITEM.put("ZEXTYPE", objectMap.get("fylx"));
                    ITEM.put("ZNUM", objectMap.get("fphm"));
                    ITEM.put("ZBLDAT", objectMap.get("fprq"));
                    ITEM.put("WRBTR", objectMap.get("hsje"));
                    ITEM.put("ZWRBTR", objectMap.get("jxszce"));
                    ITEM.put("WMWST", objectMap.get("jxse"));
                    ITEM.put("ZSL", objectMap.get("sl"));
                    ITEM.put("AUFNR", objectMap.get("nbdd"));
                    ITEM.put("SGTXT", objectMap.get("zy"));
                    ITEM.put("KOSTL", objectMap.get("cbzx"));

                    list.add(ITEM);
                    count++;
                }

            }
            map.put("ITEMS",list);

            JSONObject object = new JSONObject(map);
            baseBean.writeLog("wyq==OA-12=========object" + object.toJSONString());
            String post = YNHttpUtils.FII002(object.toJSONString(), YNHttpUtils.token());
            baseBean.writeLog("wyq==OA-12=========post" + post);

            JSONObject jsonObject = JSONObject.parseObject(post);
            JSONObject jsonObject1 = jsonObject.getJSONObject("RETURN");

            String BELNR = jsonObject1.getString("BELNR");//凭证号
            String STATUS=jsonObject1.getString("STATUS");
            String MESSAGE=jsonObject1.getString("MESSAGE");

            if (!"S".equals(STATUS)) {
                requestInfo.getRequestManager()
                        .setMessageid(requestInfo.getRequestid()+"OA-12");
                requestInfo.getRequestManager().setMessagecontent("SAP接口异常，请联系SAP人员，错误信息提示:"+MESSAGE);
                return Action.FAILURE_AND_CONTINUE;
            }



            String update = "update " + tableDBName + " set qqcs = '" + BELNR + "',qqn=?,fhn=? where requestid = '" + requestid + "'";
            baseBean.writeLog("wyq==OA-12===========update" + update);
            rs.executeUpdate(update,object.toString(),post);

        } catch (Exception e) {
            baseBean.writeLog("wyq==OA-12======exc"+e.toString());
            requestInfo.getRequestManager()
                    .setMessageid(requestInfo.getRequestid()+"OA-12");
            requestInfo.getRequestManager().setMessagecontent("OA接口异常："+e.toString());
            return Action.FAILURE_AND_CONTINUE;
        }


        return Action.SUCCESS;
    }

    /**
     * 提取明细表全部的数据
     * @param requestInfo
     * @return
     */
    private static List<Map<String, Object>> getMaps(RequestInfo requestInfo) {
        DetailTable[] detailTable = requestInfo.getDetailTableInfo().getDetailTable();
        //这里是存储了全部的明细表数据  可自行修改存储结构
        List<Map<String, Object>> detailTableMap = new ArrayList<>();
        if (detailTable.length > 0) {
            for (int i = 0; i < detailTable.length; i++) {
                DetailTable dt = detailTable[i];
                Row[] s = dt.getRow();
                for (int j = 0; j < s.length; j++) {
                    Row r = s[j];
                    Cell c[] = r.getCell();
                    Map<String, Object> objectObjectHashMap = new HashMap<>();
                    objectObjectHashMap.put("detailTableName",dt.getTableDBName());
                    for (int k = 0; k < c.length; k++) {
                        Cell c1 = c[k];
                        String name = c1.getName().toLowerCase();
                        String value = c1.getValue();
                        objectObjectHashMap.put(name, value);

                    }
                    detailTableMap.add(objectObjectHashMap);
                }
            }
        }
        return detailTableMap;
    }
}
